package com.sgb.kjwl.view.ui.activity.supplier3;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Marker;
import com.google.android.material.tabs.TabLayout;
import com.green.hand.mylibrary.SoftKeyBoardListener;
import com.im.immodel.IMUtils;
import com.sgb.alimaplibrary.MapMarkerTools;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.entity.inquiry.InquiryDetailsEntity;
import com.sgb.goods.view.activity.inquiry.InquiryPublishingActivity;
import com.sgb.goods.view.activity.inquiry.NewPurchasesActivity;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySupplier4Binding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.EnquiryImAlternateEntity;
import com.sgb.kjwl.model.entity.CallPhoneEntity;
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.supplier3.SupplierRecommendEntity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.JoinCompanyActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.supplier3.SupplierRecommendAdapter;
import com.sgb.kjwl.view.ui.adapter.supplier3.SupplierRecommendMapAdapter;
import com.sgb.kjwl.view.widget.CallPhonePopWindow;
import com.sgb.kjwl.view.widget.EnterprisePopWindow;
import com.sgb.kjwl.view.widget.EnterprisePopWindowGoods;
import com.sgb.kjwl.view.widget.ThreeButtonDialog;
import com.sgb.kjwl.viewmodel.supplier3.SupplierFragmentModel;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.MemberApplyJoinActivity;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.base.model.entity.SelectPopEntity;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.ResolutionUtil;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.inject.Inject;

import static com.swgk.core.util.ACAdminDialogUtils.MK_OURINQUIRYPRICELIST;


/**
 * @author Administrator
 */
public class NewSupplierFragment extends AppFragment {

    public static final String TYPE_LIST = "列表";
    public static final String TYPE_MAP = "图查";

    private ActivitySupplier4Binding binding;
    @Inject
    SupplierFragmentModel viewModel;
    private EnterprisePopWindow pickDistancePopWindow;
    public MapMarkerTools mapMarkerTools;
    private Marker markerLast;
    private int lastPosition = -1;
    private final List<PickSelectEntity> distanceData = new ArrayList<>();
    private SupplierRecommendAdapter supplierRecommendAdapter;
    private SupplierRecommendMapAdapter supplierRecommendAdapterBottom;
    private final HashMap<String, Object> conditionMap = new HashMap<>();
    private Double currentLat;
    private Double currentLong;

    private final List<SupplierRecommendEntity> bundles = new ArrayList<>();
    private final List<SupplierRecommendEntity> bundlesTemp = new ArrayList<>();
    private String distanceTemp = "";
    private List<MenuEntity> data;
    private EnterprisePopWindowGoods demandHallTypePopWindow;
    private int testPosition;
    private static final String SUCCESS = "SUCCESS";
    private boolean isMarkerViewChecked = false;
    private boolean isFirstFail = true;
    private float downX = 0f;
    private float downY = 0f;
    private float moveX = 0f;
    private float moveY = 0f;
    private long currentMS = 0L;
    private TranslateAnimation mapCardAnimation;

    /**
     * @param isMap
     * @param data
     * @param fromWhere 0-地图查找  1-供应商
     * @return
     */
    public static NewSupplierFragment newInstance(boolean isMap, List<MenuEntity> data, String fromWhere) {
        NewSupplierFragment fragment = new NewSupplierFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isMap", isMap);
        bundle.putString("fromWhere", fromWhere);
        bundle.putSerializable("data", (Serializable) data);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.activity_supplier4, container, false);
        initView(savedInstanceState);
        data = (List<MenuEntity>) getArguments().getSerializable("data");
        return binding.getRoot();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapMarkerTools = new MapMarkerTools(getActivity(), getLifecycle());

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initAnimator();
        init();
    }

    private void initAnimator() {
        mapCardAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                1.0f);
        mapCardAnimation.setDuration(300);
    }

    /**
     *
     */
    private void initView() {
        SelectPopEntity selectPopEntity3 = new SelectPopEntity("距离", "5", false, true);
        binding.sct.addTextButton(selectPopEntity3);
        binding.sct.onSetCallPop((position, content, bg, entity) -> {
            testPosition = position;
            if ("5".equals(entity.getType())) {
                binding.sct.contentSelect(false, true, position);
                showDistancePopWindow();
            }
        });
        binding.setViewModel(viewModel);
        binding.tvLocation.setOnClickListener(this);
        binding.searchBtn.setOnClickListener(this);
        binding.ivMap.setOnClickListener(this);
        binding.editView.setOnClickListener(this);
;
        binding.demandList.setPullRefreshEnabled(true);
        binding.demandList.setLoadingMoreEnabled(false);
        binding.demandList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getSupplierListModel(conditionMap, false);
            }

            @Override
            public void onLoadMore() {

            }
        });

        binding.etView.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                setMapCardInvisible();
                conditionMap.put("name", binding.etView.getText().toString().trim());
                viewModel.getSupplierListModel(conditionMap, false);
                return true;
            }
            return false;
        });
        viewModel.getMenuModel();
        initListener();
    }


    public void showecommendCategoryData(List<MenuEntity>data){
        this.data = data;
//        MenuEntity menuEntity = new MenuEntity();
//        menuEntity.setName("全部");
//        menuEntity.setId("");
//        data.add(0, menuEntity);
        binding.etView.setHint("搜索供应商名称");
        conditionMap.put("cid1", "");
        conditionMap.put("distance", "10000000");
        getDemanHallTabList(setSecondTypeData(data));
    }

    private void initListener() {
        SoftKeyBoardListener.setListener(requireActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {//键盘处于打开状态
                binding.etView.setCursorVisible(true);// 显示光标
                isFilterViewVisibility(true);
            }

            @Override
            public void keyBoardHide(int height) {//键盘处于关闭状态
                binding.etView.setCursorVisible(false);// 隐藏光标
            }
        });
    }

    private void init() {
        demandHallTypePopWindow = new EnterprisePopWindowGoods(getActivity());
        demandHallTypePopWindow.setBgView(binding.grayLayout);
        demandHallTypePopWindow.setOnResultClick((key1, key2, key3) -> {
            binding.tabLayout.getTabAt((int) key3).select();
            if ("全部".equals(data.get((int) key3).getName() + "")) {
                conditionMap.put("cid1", "");
            } else {
                conditionMap.put("cid1", data.get((int) key3).getId() + "");
            }
            viewModel.getSupplierListModel(conditionMap, false);
        });
        demandHallTypePopWindow.setOnDisMissClick(() -> binding.editView.setImageResource(R.drawable.btn_down));
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setMapCardInvisible();
                setTabLayoutName(tab.getPosition());
                demandHallTypePopWindow.setDefData(tab.getPosition());
                if (tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tabSelect.setTextColor(getResources().getColor(R.color.APPTabColor));
                    tabSelect.invalidate();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab != null && tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    tabSelect.setTextColor(getResources().getColor(R.color.color_666666));
                    tabSelect.invalidate();
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        pickDistancePopWindow = new EnterprisePopWindow(getActivity());
        pickDistancePopWindow.setBgView(binding.grayLayout);
        pickDistancePopWindow.setOnResultClick((key1, key2, key3) -> {
            distanceTemp = (String) key2;
            setMapCardInvisible();
            if ("不限".equals(distanceTemp)) {
                conditionMap.put("distance", "10000000");
            } else {
                conditionMap.put("distance", ((String) key2).replace("KM", ""));
            }
            viewModel.getSupplierListModel(conditionMap, false);
        });

        pickDistancePopWindow.setOnDisMissClick(() -> {
            binding.sct.contentSelect(null != distanceTemp && !"不限".equals(distanceTemp) && !"".equals(distanceTemp), false, testPosition);
        });

        if (binding.tvMap.getText().toString().equals(TYPE_MAP)) {
            binding.tvMap.setText(TYPE_MAP);
            binding.demandList.setVisibility(View.VISIBLE);
            binding.flMap.setVisibility(View.GONE);
            binding.mapView.setVisibility(View.GONE);
        } else {
            binding.tvMap.setText(TYPE_LIST);
            binding.demandList.setVisibility(View.GONE);
            binding.flMap.setVisibility(View.VISIBLE);
            binding.mapView.setVisibility(View.VISIBLE);
        }
        binding.tvLocation.setVisibility(View.VISIBLE);
        binding.vLine.setVisibility(View.VISIBLE);
    }

    private void resetMarker(String curMarkerId, Marker markerNew, int pos, String type) {
        if (null != markerLast) {
            BitmapDescriptor bitmapSmall;
            if ("1".equals(type)) {
                bitmapSmall = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getActivity().getResources(), R.mipmap.wt_pub));
            } else {
                bitmapSmall = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getActivity().getResources(), R.mipmap.wt_goods));
            }
            markerLast.setIcon(bitmapSmall);
        }

    }

    private void initView(Bundle savedInstanceState) {
        supplierRecommendAdapter = new SupplierRecommendAdapter(getActivity(), null);
        supplierRecommendAdapterBottom = new SupplierRecommendMapAdapter(getActivity(), null);
        binding.demandList.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.goodsList.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.demandList.swapAdapter(supplierRecommendAdapter, true);
        binding.goodsList.swapAdapter(supplierRecommendAdapterBottom, true);
        viewModel.getDistanceModel();
        MapView mMapView = binding.mapView;
        mMapView.getMap().setOnMapClickListener(latLng -> {
            if (isMarkerViewChecked) {
                isMarkerViewChecked = false;
            } else {
                if (binding.showList.getVisibility() == View.VISIBLE) {
                    setMapCardInvisible();
                }
            }
        });
        mMapView.getMap().setOnMapTouchListener(event -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downX = event.getX();//float downX
                    downY = event.getY();//float DownY
                    moveX = 0;
                    moveY = 0;
                    currentMS = System.currentTimeMillis();//long currentMS     获取系统时间
                    break;
                case MotionEvent.ACTION_MOVE:
                    moveX += Math.abs(event.getX() - downX);//X轴距离
                    moveY += Math.abs(event.getY() - downY);//y轴距离
                    downX = event.getX();
                    downY = event.getY();
                    break;
                case MotionEvent.ACTION_UP:
                    long moveTime = System.currentTimeMillis() - currentMS;//移动时间
                    //判断是否继续传递信号
                    if (moveTime > 200 && (moveX > 20 || moveY > 20)) {
                        isFilterViewVisibility(false);
                        //不再执行后面的事件，在这句前可写要执行的触摸相关代码。点击事件是发生在触摸弹起后
                    }
                    break;
                default:
                    break;
            }
        });

        mapMarkerTools.init(savedInstanceState, mMapView);
        mapMarkerTools.setMarkerClick(new MapMarkerTools.MarkerClick() {
            @Override
            public void onMarkerClick(int pos, String title) {

            }

            @Override
            public void onMarkerClick(int pos, String title, Marker marker) {
                isMarkerViewChecked = true;
                showMarkerView(pos, title);
                BitmapDescriptor bitmapSmall = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getActivity().getResources(), R.mipmap.wt_pub_big));
                marker.setIcon(bitmapSmall);
                if (lastPosition == Integer.parseInt(title)) {
                    return;
                }
                resetMarker(marker.getId(), marker, pos, "1");

                markerLast = marker;
                lastPosition = Integer.parseInt(title);
                mapMarkerTools.jumpPoint(marker);
            }

            @Override
            public void onLocationChanged(Double Lat, Double Log, String address) {
                if (currentLat == null || currentLat <= 0) {
                    currentLat = Lat;
                    currentLong = Log;
                    //设置经纬度以查询地图模式下的数据
                    conditionMap.put("latitude", currentLat);
                    conditionMap.put("longitude", currentLong);
                    mapMarkerTools.mapClear();
                    viewModel.getSupplierListModel(conditionMap, false);

                    cameraToPosition();
                }
            }

            @Override
            public void getAddress(Double Lat, Double Log, String address) {

            }

            @Override
            public void failure() {
                //未开启定位权限，该回调会重复调用
                if (isFirstFail)
                    viewModel.getSupplierListModel(conditionMap, false);
                isFirstFail = false;

            }
        });

        supplierRecommendAdapter.setOnItemClick(new AdapterOnItemClick<SupplierRecommendEntity>() {
            @Override
            public void onItemClick(SupplierRecommendEntity supplierRecommendEntity, int position) {
                if (TextUtils.isEmpty(supplierRecommendEntity.getNo())) {
                    ToastUtil.show(getActivity(), "企业店铺No不能为空");
                    return;
                }
                WebsiteInfoActivity.start(getActivity(), supplierRecommendEntity.getNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY, 0, 0);
            }
        });

        supplierRecommendAdapterBottom.setActionCallBack((type, recommendEntity) -> {
            switch (type) {
                case 1://交流
                    if (!UserOperating.getInstance().isLogged()) {
                        VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
                    } else {
                        viewModel.getGoodsImAccount(recommendEntity.getCompanyId(),3);
                    }
                    break;
                case 2://询价
                    inquiryPublish(recommendEntity);
                    break;
                case 3://函询
                    ToastUtil.show(getActivity(), "功能开发中");
                    break;
                case 4://申请
                    applyJoin(recommendEntity);
                    break;
                case 5://加盟
                    inviteJoin(recommendEntity);
                    break;
                case 6:
                    if (TextUtils.isEmpty(recommendEntity.getNo())) {
                        ToastUtil.show(getActivity(), "企业店铺No不能为空");
                        return;
                    }
                    WebsiteInfoActivity.start(getActivity(), recommendEntity.getNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY, 0, 0);
                    break;
                default:
                    break;
            }
        });
    }

    private void isFilterViewVisibility(boolean isVisibility) {
        if (isVisibility) {
            if (binding.filterContainer.getVisibility() == View.GONE) {
                binding.filterContainer.setVisibility(View.VISIBLE);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.llGoodsTag.getLayoutParams();
                layoutParams.topMargin = ResolutionUtil.dp2px(getActivity(), 90);
                binding.llGoodsTag.setLayoutParams(layoutParams);
            }
        } else {
            if (binding.filterContainer.getVisibility() == View.VISIBLE) {
                binding.filterContainer.setVisibility(View.GONE);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.llGoodsTag.getLayoutParams();
                layoutParams.topMargin = ResolutionUtil.dp2px(getActivity(), 40);
                binding.llGoodsTag.setLayoutParams(layoutParams);
            }
        }
    }

    private void setMapCardInvisible() {
        if (mapCardAnimation != null && binding.showList.getVisibility() == View.VISIBLE) {
            binding.showList.startAnimation(mapCardAnimation);
            binding.showList.setVisibility(View.GONE);
            resetMarker("", null, 0, "1");
        }
    }

    /**
     * 邀请加盟
     *
     * @param entity
     */
    private void inviteJoin(SupplierRecommendEntity entity) {
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            showLogInDialog();
        } else {
            int type = UserOperating.getInstance().getUserIdentity();
            if (type != 1) {
                showNotEnterpriseDialog();
                return;
            }
            Map<String, String> map = new HashMap<>();
            map.put("siteNo", entity.getNo());
            map.put("siteType", "1");
            viewModel.getWebsiteInfo(map, entity.getNo(), 2);
        }
    }

    private void applyJoin(SupplierRecommendEntity entity) {
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            showLogInDialog();
        } else {
            int type = UserOperating.getInstance().getUserIdentity();
            if (type != 1) {
                showNotEnterpriseDialog();
                return;
            }
            Map<String, String> map = new HashMap<>();
            map.put("siteNo", entity.getNo());
            map.put("siteType", "1");
            viewModel.getWebsiteInfo(map, entity.getNo(), 1);
        }
    }

    public void showWebsiteInfo(WebsiteInfoEntity entity, String websiteNo, int type) {
        viewModel.getPermissionMenu(entity, 1, websiteNo, entity.getName(), type);
    }

    public void getPermission(WebsiteInfoEntity entity, int websiteType, String websiteNo, String companyName, int type) {
        if (type == 1) {
            QualityMemberBean bean = new QualityMemberBean();
            bean.setCompanyNo(websiteNo);
            bean.setCompanyName(companyName);
            MemberApplyJoinActivity.start(getActivity(), bean);

        } else {
            QualityMemberBean bean1 = new QualityMemberBean();
            bean1.setCompanyNo(websiteNo);
            bean1.setCompanyName(entity.getName());
            bean1.setServiceTypeName(entity.getServiceTypeName());
            bean1.setServiceType(entity.getServiceType());
            MemberInviteJoinActivity.start(getActivity(), bean1);
        }
    }

    /**
     * 未登录弹框跳转认证
     */
    public void showLogInDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_message = view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("温馨提示");
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("确定");
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("未登录，请先登录。");
        tv_logout_confirm.setOnClickListener(v -> {
            VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_MAIN_ACTIVITY_JUMP);
            roundCornerDialog.dismiss();
        });
        tv_logout_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    /***
     * 团队加入企业-提示弹窗
     * @param
     */
    private void showJoin2Dialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_map_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        TextView tvConfirm = view.findViewById(R.id.tv_confirm);
        tv_message.setText("请将身份切换到企业或者加入\n已认证的企业后再试");
        tvConfirm.setOnClickListener(v -> {
            JoinCompanyActivity.start(getActivity());
            roundCornerDialog.dismiss();
        });
        tvCancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    /***
     * 提示弹窗
     * @param
     * @param
     */
    private void showNotEnterpriseDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_one_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_message = view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.GONE);
        tv_message.setText("您当前为个人/团队身份，暂不\n支持该操作");
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("知道了");
        tv_logout_confirm.setTextColor(getActivity().getResources().getColor(R.color.color_5792FD));
        tv_message.setTextColor(getActivity().getResources().getColor(R.color.color_666666));
        tv_message.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv_logout_confirm.setOnClickListener(v -> roundCornerDialog.dismiss());
    }


    /**
     * 询价
     */
    private void inquiryPublish(SupplierRecommendEntity entity) {
        if (authentication()) {
            viewModel.getCheckUserInfo(entity);
        }
    }

    /**
     * 需要实现
     */
    public void buildInquirySupplierParam(SupplierRecommendEntity entity) {
        List<InquiryDetailsEntity.InviteCompanyList> companyListDTOS = new ArrayList<>();
        InquiryDetailsEntity.InviteCompanyList inviteCompanyListDTO = new InquiryDetailsEntity.InviteCompanyList();
        inviteCompanyListDTO.setSupplier(entity.getNo());
        inviteCompanyListDTO.setSupplierName(entity.getName());
        inviteCompanyListDTO.setProvinceNo(entity.getProvinceNo());
        inviteCompanyListDTO.setProvinceName(entity.getProvinceName());
        companyListDTOS.add(inviteCompanyListDTO);
        Intent createGoods = new Intent(getActivity(), InquiryPublishingActivity.class);
        getActivity().startActivity(createGoods);
        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheGoodsSupplierModel, companyListDTOS);
    }

    private boolean authentication() {
        //跳转到询价页面前需用户认证
        if (!UserOperating.getInstance().isLogged()) {
            VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
            return false;
        }
        int type = UserOperating.getInstance().getUserIdentity();
        if (type == 0) {
            if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                //个人未实名认证--实名认证或加入企业
                new ThreeButtonDialog.Builder(getActivity())
                        .title("温馨提示")
                        .content("您没有权限，请认证或加入企业后再试")
                        .confirmCallback(v -> {
                            //实名认证
                            AuthActivity3.start(getActivity());
                        }).joinCallback(v -> {
                    //去加入企业
                    JoinCompanyActivity.start(getActivity());
                }).show();
                return false;
            }

        } else if (type == 1) {
            int type1 = ACAdminDialogUtils.isPermissionForAsk(MK_OURINQUIRYPRICELIST, false);
            if (type1 != ACAdminDialogUtils.TYPE_NORMAL /*&& !SUCCESS.equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, ""))*/) {
                MToast.showToast(getActivity(), "您没有权限，请联系管理员开通");
                return false;
            }
        } else if (type == 2) {
            showJoin2Dialog();
            return false;
        }
        return true;
    }

    /**
     * 获取tab页签名称
     *
     * @param position
     */
    private void setTabLayoutName(int position) {
        if (null != data && data.size() > 0) {
            if ("全部".equals(data.get(position).getName() + "")) {
                conditionMap.put("cid1", "");
            } else {
                conditionMap.put("cid1", data.get(position).getId());
            }
            viewModel.getSupplierListModel(conditionMap, false);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_close:
                binding.showList.setVisibility(View.GONE);
                break;
            case R.id.iv_back:
                getActivity().finish();
                break;
            case R.id.tv_location:
                if (binding.showList.getVisibility() == View.VISIBLE) {
                    setMapCardInvisible();
                }
                Intent intent = new Intent();
                intent.setClass(getActivity(), SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "选择区域");
                intent.putExtra(SelectAddressActivity.SHOW_DELETE, "SHOW_DELETE");
                intent.putExtra(SelectAddressActivity.LATITUDE, currentLat);
                intent.putExtra(SelectAddressActivity.LONGTITUDE, currentLong);
                startActivityForResult(intent, 101);
                break;
            case R.id.edit_view:
                if (null == data || data.size() == 0) {
                    return;
                }
                binding.editView.setImageResource(R.drawable.btn_shop_up);
                demandHallTypePopWindow.showPopwindow(binding.viewLine, 0, 0);
                demandHallTypePopWindow.setData(setSecondTypeData(data));
                break;
            case R.id.iv_map:
                if (binding.tvMap.getText().toString().equals(TYPE_MAP)) {
                    binding.tvMap.setText(TYPE_LIST);
                    binding.ivMap.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.mipmap.icon_search_map));
                    binding.demandList.setVisibility(View.GONE);
                    binding.flMap.setVisibility(View.VISIBLE);
                    binding.mapView.setVisibility(View.VISIBLE);
                } else {
                    binding.tvMap.setText(TYPE_MAP);
                    binding.ivMap.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.mipmap.icon_search_list));
                    RecyclerView.Adapter listAdapter = binding.demandList.getAdapter();
                    if (listAdapter != null && listAdapter.getItemCount() > 0) {
                        binding.demandList.setVisibility(View.VISIBLE);
                        binding.emptyView.setVisibility(View.GONE);
                    } else {
                        binding.emptyView.setVisibility(View.VISIBLE);
                    }
                    binding.flMap.setVisibility(View.GONE);
                    binding.mapView.setVisibility(View.GONE);
                }
                binding.tvLocation.setVisibility(View.VISIBLE);
                binding.vLine.setVisibility(View.VISIBLE);
                break;

            case R.id.search_btn:
                setMapCardInvisible();
                conditionMap.put("name", binding.etView.getText().toString().trim());
                viewModel.getSupplierListModel(conditionMap, false);
                break;
            default:
                break;
        }
    }

    private List<PickSelectEntity> setSecondTypeData(List<MenuEntity> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (MenuEntity entity : data) {
                PickSelectEntity dictEntity3 = new PickSelectEntity();
                dictEntity3.setNo(entity.getId());
                dictEntity3.setProjectscale(entity.getName());
                types.add(dictEntity3);
            }
        }
        return types;
    }

    public void getDemanHallTabList(List<PickSelectEntity> data) {
        if (null != data && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                binding.tabLayout.addTab(binding.tabLayout.newTab());
                binding.tabLayout.getTabAt(i).setCustomView(R.layout.tab_item_textview);
                TextView tv = binding.tabLayout.getTabAt(i).getCustomView().findViewById(R.id.tv_tab_item_textview);
                tv.setText(data.get(i).getProjectscale());
                if (i == 0) {
                    tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tv.setTextColor(getResources().getColor(R.color.APPTabColor));
                }
            }
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }

    private void showDistancePopWindow() {
        pickDistancePopWindow.showPopwindowGoods(binding.sct);
        pickDistancePopWindow.setData(distanceData);
    }


    public void showDistancePopWindow(List<DictEntity3> data) {
        setSecondDistanceData(data);
        if (data != null && data.size() > 0) {
            conditionMap.put("distance", "10000000");
        }
        pickDistancePopWindow.setData(distanceData);
    }

    private void setSecondDistanceData(List<DictEntity3> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (DictEntity3 entity : data) {
                PickSelectEntity pickSelectEntity = new PickSelectEntity();
                pickSelectEntity.setNo(entity.getId());
                pickSelectEntity.setProjectscale(entity.getName());
                types.add(pickSelectEntity);
            }
        }
        distanceData.clear();
        PickSelectEntity entityTemp = new PickSelectEntity();
        entityTemp.setNo("10000000");
        entityTemp.setProjectscale("不限");
        distanceData.addAll(types);
        distanceData.add(0, entityTemp);
    }

    public void showList(List<SupplierRecommendEntity> data, boolean isLoadMore) {
        if (isLoadMore) {
            binding.demandList.loadMoreComplete();
            if (data.size() != 0) {
                supplierRecommendAdapter.addDatas(data);
            }
        } else {
            binding.demandList.setAdapter(supplierRecommendAdapter);
            binding.demandList.refreshComplete();
            if (data.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.demandList.setLoadingMoreEnabled(false);
                binding.demandList.setVisibility(View.GONE);
            } else {
                binding.demandList.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                binding.demandList.setLoadingMoreEnabled(false);
                binding.demandList.loadMoreComplete();
            }
            supplierRecommendAdapter.setDatas(data);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && data != null) {
            currentLat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            currentLong = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            conditionMap.put("latitude", currentLat);
            conditionMap.put("longitude", currentLong);
            viewModel.getSupplierListModel(conditionMap, false);
            cameraToPosition();
        }
    }

    /**
     * 设置定位点
     */
    private void cameraToPosition() {
        mapMarkerTools.setMyLocation(currentLat, currentLong);
    }

    public void showMap(List<SupplierRecommendEntity> data, boolean isLoadMore) {
        addMarkInfoWindow(data, isLoadMore);
    }

    private void addMarkInfoWindow(List<SupplierRecommendEntity> data, boolean isLoadMore) {
        try {
            bundles.clear();
            bundlesTemp.clear();
            if (data.size() == 0) {
                mapMarkerTools.mapClear();
                return;
            }
            if (!isLoadMore) {
                mapMarkerTools.mapClear();
            }
            bundles.addAll(data);
            bundlesTemp.addAll(data);
            ListIterator<SupplierRecommendEntity> listIterator = bundlesTemp.listIterator();
            while (listIterator.hasNext()) {
                SupplierRecommendEntity next = listIterator.next();
                for (SupplierRecommendEntity recommendEntity : bundlesTemp) {
                    if (next.getLatitude().equals(recommendEntity.getLatitude()) && next.getLongitude().equals(recommendEntity.getLatitude())) {
                        listIterator.remove();
                    }
                }
            }

            for (int i = 0; i < bundlesTemp.size(); i++) {
                SupplierRecommendEntity entity = bundlesTemp.get(i);
                if (null != entity && !TextUtils.isEmpty(entity.getLatitude()) && !TextUtils.isEmpty(entity.getLongitude())) {
                    double currentLat = Double.parseDouble(entity.getLatitude());
                    double currentLong = Double.parseDouble(entity.getLongitude());
                    if (currentLat == 0 || currentLong == 0) {
                        continue;
                    }
                    mapMarkerTools.addPoiItem(currentLat, currentLong, "");
                }
            }
            mapMarkerTools.addAllMarkerToMap(R.mipmap.wt_pub, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showMarkerView(int pos, String title) {
        SupplierRecommendEntity entity = bundlesTemp.get(Integer.parseInt(title));
        List<SupplierRecommendEntity> tempList = new ArrayList<>();
        for (int i = 0; i < bundles.size(); i++) {
            String tempLatitude = bundles.get(i).getLatitude();
            String tempLongitude = bundles.get(i).getLongitude();
            if (entity.getLatitude().equals(tempLatitude) && entity.getLongitude().equals(tempLongitude)) {
                tempList.add(bundles.get(i));
            }
        }
        binding.showList.setVisibility(View.VISIBLE);
        binding.goodsList.setAdapter(supplierRecommendAdapterBottom);
        supplierRecommendAdapterBottom.setDatas(tempList);
    }

    public void showImWindow(List<EnquiryImAlternateEntity.CompanyCustomersDTO> companyCustomers) {
        if (companyCustomers.size() == 1) {
            if (companyCustomers.get(0) != null && !TextUtils.isEmpty(String.valueOf(companyCustomers.get(0).getImAccount()))) {
                IMUtils.getInstance().buildSingleTalking(String.valueOf(companyCustomers.get(0).getImAccount()));
            }
        } else {
            List<CallPhoneEntity> datas = new ArrayList<>();
            for (int i = 0; i < companyCustomers.size(); i++) {
                CallPhoneEntity entity = new CallPhoneEntity();
                entity.setType("1");
                entity.setPrincipalName(companyCustomers.get(i).getPrincipalName());
                entity.setImAccount(companyCustomers.get(i).getImAccount());
                entity.setImToken(companyCustomers.get(i).getImToken());
                datas.add(entity);
            }
            CallPhonePopWindow window = new CallPhonePopWindow(getActivity());
            window.setBgView(binding.grayLayout);
            window.setData(datas);
            if (!window.isShowing()) {
                window.showDownPopwindow(binding.grayLayout, true);
            }
        }
    }
}
